﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace Hvam.SharePoint.Features.IIS {
    public class IISFeatureReceiver : SPFeatureReceiver {
        public override void FeatureActivated(SPFeatureReceiverProperties properties) {
            var service = IISManagementService.Local;

            if (service == null) {
                service = new IISManagementService(SPFarm.Local);
                service.Update();
            }

            // I can't seem to get my job running under my IISManagementService service, anyone got any ideas?
            var jobService = SPFarm.Local.Services.GetValue<SPWebService>(string.Empty);
            var definition = new IISManagementUpdaterJob(IISManagementUpdaterJob.PreferredName, jobService);

            var schedule = IISManagementUpdaterJob.PreferredSchedule;
            var property = properties.Definition.Properties["JobSchedule"];
            if (property!=null) {
                schedule=SPSchedule.FromString(property.Value);
            }

            definition.Schedule = schedule;
            definition.Title = IISManagementUpdaterJob.PreferredTitle;
            definition.Update();
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
            var jobService = SPFarm.Local.Services.GetValue<SPWebService>(string.Empty);

            (from j in jobService.JobDefinitions where j.Name == IISManagementUpdaterJob.PreferredName select j).ToList().ForEach(j => j.Delete());

            IISManagementService.Local.Delete();
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties) { }
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties) { }
    }
}
